/*
http://hadoop.apache.org/docs/r3.3.0/hadoop-mapreduce-client/hadoop-mapreduce-client-core/MapReduceTutorial.html#Example:_WordCount_v2.0
官网 WordCount2.0 已解决大小写问题，只能忽略punctuation.txt文件
TODO
* 忽略标点符号、数字
* 忽略停词
* 单词长度>=3
* 按单词出现次数从大到小排序，输出格式"<排名>：<单词>，<次数>“
* 输出前100个高频单词
 */

package wc2;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.*;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.StringUtils;

public class WordCount2 {

    public static class TokenizerMapper
            extends Mapper<Object, Text, Text, IntWritable>{

        static enum CountersEnum { INPUT_WORDS }

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        private boolean caseSensitive; //大小写
        private Set<String> patternsToSkip = new HashSet<String>(); //停词

        private Configuration conf;
        private BufferedReader fis;

        @Override
        public void setup(Context context) throws IOException,
                InterruptedException {
            conf = context.getConfiguration();
            //caseSensitive = conf.getBoolean("wordcount.case.sensitive", true);
            caseSensitive = conf.getBoolean("wordcount.case.sensitive", false); //默认忽略大小写
            if (conf.getBoolean("wordcount.skip.patterns", false)) {
                URI[] patternsURIs = Job.getInstance(conf).getCacheFiles(); //cachedfiles里存储停词
                for (URI patternsURI : patternsURIs) {
                    Path patternsPath = new Path(patternsURI.getPath());
                    String patternsFileName = patternsPath.getName().toString();
                    parseSkipFile(patternsFileName);
                }
            }
        }

        private void parseSkipFile(String fileName) {
            try {
                fis = new BufferedReader(new FileReader(fileName));
                String pattern = null;
                while ((pattern = fis.readLine()) != null) {
                    patternsToSkip.add(pattern);    //所有停词都放在patternsToSkip中0
                }
            } catch (IOException ioe) {
                System.err.println("Caught exception while parsing the cached file '"
                        + StringUtils.stringifyException(ioe));
            }
        }

        @Override
        public void map(Object key, Text value, Context context
        ) throws IOException, InterruptedException {
            String line = (caseSensitive) ?
                    value.toString() : value.toString().toLowerCase();  //大小写
            /*for (String pattern : patternsToSkip) {
                line = line.replaceAll(pattern, "");
            }*/ //自带skippattern只适用标点，停词文件使用的话把遇到的单词中的也给删除了
            StringTokenizer itr = new StringTokenizer(line);
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                String wordorigin = word.toString();    //把Text转换为String类型
                String regEx = "[`~☆★!@#$%^&*()+=|{}':;,\\[\\]》·.<>/?~！@#￥%……（）——+|{}【】‘；：”“’。\"，\\-、？]";   //正则表达式
                String word1 = wordorigin.replaceAll(regEx,"");
                word = new Text(word1);
                if(word.getLength()>=3 && (!patternsToSkip.contains(word.toString()))){ //对每一个word判断是否需要skip(长度+停词)
                    context.write(word, one);
                    Counter counter = context.getCounter(CountersEnum.class.getName(),
                            CountersEnum.INPUT_WORDS.toString());
                    counter.increment(1);
                }

            }
        }
    }

    public static class IntSumReducer
            extends Reducer<Text,IntWritable,Text,IntWritable> {
        private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    //TODO:FormatReducer.class
    public static class FormatReducer
            extends Reducer<IntWritable,Text,Text, NullWritable>{ //key,value已经对换
        private int count = 0;
        public void reduce(IntWritable key,Iterable<Text> values,Context context) throws IOException,InterruptedException{
            for(Text v:values)
            {
                if(count==100) return;
                count++;
                String vs = v.toString();
                String res = count+":"+vs+","+key.toString();
                context.write(new Text(res),NullWritable.get());    //全放入key中，value赋为Null
            }
        }
    }

    //TODO:AutoDecreasingComparator.class
    //key,value已经转换，将super的结果添负号即可
    private static class AutoDecreasingComparator extends IntWritable.Comparator{
        public int compare(WritableComparable a, WritableComparable b){
            return -super.compare(a,b);
        }
        public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2){
            return -super.compare(b1,s1,l1,b2,s2,l2);
        }
    }



    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        GenericOptionsParser optionParser = new GenericOptionsParser(conf, args);
        String[] remainingArgs = optionParser.getRemainingArgs();
        if ((remainingArgs.length != 2) && (remainingArgs.length != 4)) {
            System.err.println("Usage: wordcount <in> <out> [-skip skipPatternFile]");
            System.exit(2);
        }
        Job job = Job.getInstance(conf, "word count");
        job.setJarByClass(wc2.WordCount2.class);
        job.setMapperClass(wc2.WordCount2.TokenizerMapper.class);
        job.setCombinerClass(wc2.WordCount2.IntSumReducer.class);
        job.setReducerClass(wc2.WordCount2.IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        List<String> otherArgs = new ArrayList<String>();
        for (int i=0; i < remainingArgs.length; ++i) {
            if ("-skip".equals(remainingArgs[i])) {
                job.addCacheFile(new Path(remainingArgs[++i]).toUri());
                job.getConfiguration().setBoolean("wordcount.skip.patterns", true);
            } else {
                otherArgs.add(remainingArgs[i]);
            }
        }
        FileInputFormat.addInputPath(job, new Path(otherArgs.get(0)));
        //第一步job输出到临时目录中
        Path tempDir = new Path("wordcount-temp-"+Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
        FileOutputFormat.setOutputPath(job,tempDir);

        job.setOutputFormatClass(org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat.class);

        if(job.waitForCompletion(true))
        {
            Job sortJob = Job.getInstance(conf,"sort");
            sortJob.setJarByClass(WordCount2.class);
            FileInputFormat.addInputPath(sortJob,tempDir);
            sortJob.setInputFormatClass(org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat.class);

            sortJob.setMapperClass(org.apache.hadoop.mapreduce.lib.map.InverseMapper.class); //hadoop库提供，map()数据对key,value交换

            sortJob.setReducerClass(FormatReducer.class); //TODO:输出格式&输出前100个

            sortJob.setSortComparatorClass(AutoDecreasingComparator.class);  //TODO:实现降序排序类
            sortJob.setNumReduceTasks(1); //Reducer个数限定为1，表示最终输出结果文件为1

            sortJob.setOutputKeyClass(IntWritable.class);
            sortJob.setOutputValueClass(Text.class);
            FileOutputFormat.setOutputPath(sortJob,new Path(otherArgs.get(1)));
            System.exit(sortJob.waitForCompletion(true)?0:1);
        }


        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}